<template>
  <el-dialog
    v-dialogDrag
    top="1vh"
    :before-close="dialogClose"
    width="60%"
    :visible="isEditDialogShow"
    append-to-body
  >
    <div slot="title">
      <div class="edit-title">
        <label>指标修改</label>
        <div>
          <span>单号:</span>
          <span>{{ connectStore.value.rowNow.code }}</span>
        </div>
      </div>
    </div>
    <!--//!  form -->
    <div class="dialog-container">
      <div class="edit-detailCode">
        <span>明细号:</span>
        <span>{{ connectStore.value.rowNow.rn }}</span>
      </div>
      <div class="edit-form">
        <el-form ref="form" :model="cacheItem" label-width="120px">
          <el-col
            v-for="(item, index) in formColunms"
            :key="index"
            :span="11"
          >
            <el-form-item :label="item.label">
              <div v-if="item.type === 1">
                <el-date-picker
                  v-model="cacheItem[item.key]"
                  :type="item.inputType"
                  :value-format="item.valueFormatter"
                  :placeholder="item.placeholder"
                  style="width: 100%;"
                />
              </div>

              <div v-if="item.type === 3">
                <el-input
                  v-model="cacheItem[item.key]"
                  :placeholder="item.placeholde"
                  :type="item.inputType"
                />
              </div>

              <div v-if="item.type === 4">
                <el-select
                  v-model="cacheItem[item.itemKey]"
                  style="width:100%"
                  :value-key="item.resKey"
                  filterable
                  clearable
                  :placeholder="item.placeholder"
                  @focus="getSelectFouce(item)"
                  @change="(value) => selectChange(value, item)"
                >
                  <el-option
                    v-for="(item1,index1) in item.opintion"
                    :key="index1"
                    :label="item1[item.showLabel]"
                    :value="item1[item.resKey]"
                  />
                </el-select>
              </div>

              <div v-if="item.type === 5">
                <Select-Tree
                  :item="item"
                  :choose-year="chooseYear"
                  :common-index="index"
                  :label="item.showValue"
                  :show-label="item.showLabel"
                  :item-url="item.url"
                  :placeholder="item.placeholder"
                  :common-values="cacheItem[item.itemKey]"
                  @changeData="changeSelectTreeData"
                />
              </div>

              <div v-if="item.type === 7">
                <el-upload
                  class="upload-demo"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :on-change="(file, fileList) => onFileChange(file, fileList, item)"
                  :before-remove="onFileRemove"
                  :file-list="cacheItem[item.key]"
                  :auto-upload="false"
                  :on-preview="onFileView"
                  multiple
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </div>

              <div v-if="item.type === 8">
                <el-autocomplete
                  v-model="cacheItem[item.itemKey]"
                  :fetch-suggestions="(query, cb) => querySearchAsync(query, cb, cacheItem)"
                  placeholder="请输入内容"
                  @blur="({target: {value}}) => inputCompleteBlur(value, cacheItem)"
                  @select="(value) => handleSelect(value, cacheItem)"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogClose">取 消</el-button>
      <el-button :loading="submitLoading" type="primary" @click="submit">提 交</el-button>
    </span>
  </el-dialog>
</template>

<script type="text/ecmascript-6">
import _ from 'lodash';
import SelectTree from '@/views/indexInput/components/SelectTree.vue';
import { getCommonDataSource } from '@/api/reportCenter';
import { editBudget } from '@/api/indexInput';
import { uploadMulti } from '@/api/file';

/*
{
    "programCode":"330604202103300000007",
        "programName":"eee",
        "enterpriseGuid":"135",
        "enterpriseCode":"135",
        "enterpriseName":"1335",
        "divisionGuid":"135",
        "divisionName":"135",
        "functionCode":"135",
        "functionGuid":"135",
        "functionName":"135",
        "resourceGuid":"135",
        "resourceCode":"135",
        "resourceName":"135",
        "budgetcategoryGuid":"135",
        "budgetcategoryCode":"135",
        "budgetcategoryName":"135",
        "money":"135",
        "fileNo":"135",
        "postFileDate":"2021-01-30",
        "originalFileNo":"12",
        "originalFileDate":"2021-01-30",
        "accountDate":"2021-01-30",
        "remark":"13",
        "annex":"13;1212;",
        "year":2021,
        "guid":"10"
}
*/
export default {
  inject: ['connectStore'],
  components: {
    SelectTree
  },
  data() {
    return {
      submitLoading: false,
      cacheItem: {},
      chooseYear: '',
      // 1 时间 3输入框 4下拉框 5树下拉框  7fu'j 8远程搜索
      formColunms: [
        {
          type: 1,
          value: '',
          key: 'year',
          label: '年份',
          placeholder: '请选择年份',
          inputType: 'year',
          valueFormatter: 'yyyy'

        },

        // {
        //   type: 4,
        //   value: '',
        //   key: 'divisionGuid',
        //   itemKey: 'divisionName', // 关联cache
        //   resKey: 'divisionName',
        //   label: '归口',
        //   placeholder: '请选择归口',
        //   url: 'jc/getDivisionByEnter',
        //   opintion: [],
        //   showLabel: 'divisionName',
        //   showValue: 'divisionGuid',
        //   requestKey: 'divisionGuid',
        //   bindKey: ['divisionGuid'],
        //   bindKeyRes: ['divisionGuid']
        // },

        {
          type: 1,
          value: '',
          key: 'postFileDate',
          label: '发文日期',
          placeholder: '请选日期',
          inputType: 'date',
          valueFormatter: 'yyyy-MM-dd'
        },

        {
          type: 1,
          value: '',
          key: 'originalFileDate',
          label: '原发文日期',
          placeholder: '请选择',
          inputType: 'date',
          valueFormatter: 'yyyy-MM-dd'
        },

        {
          type: 8,
          itemKey: 'programName',
          value: '',
          loading: false,
          label: '项目名称',
          placeholder: '请输入',
          options: [],
          showLabel: 'programName',
          key: 'programCode',
          url: 'budget/in/getProgramList'
        },

        {
          type: 5,
          label: '功能科目',
          placeholder: '请选择',
          itemKey: 'functionName',
          formType: '0',
          url: 'jc/getFunctionSection',
          value: '',
          symbol: 'eq',
          showLabel: 'functionSectionText',
          key: 'functionSectionText',
          requestKey: 'functionCode',
          bindKey: ['functionCode', 'functionGuid', 'functionName'],
          bindKeyRes: ['functionSectionCode', 'functionSectionGuid', 'functionSectionName']
        },

        {
          type: 4,
          value: '',
          itemKey: 'resourceName',
          resKey: 'resourceCateName',
          label: '资金来源',
          placeholder: '请选择归口',
          url: 'jc/getResource',
          chooseItem: {},
          opintion: [],
          showLabel: 'resourceCateText',
          showValue: 'resourceCateCode',
          requestKey: 'divisionGuid',
          bindKey: ['resourceGuid', 'resourceCateCode'],
          bindKeyRes: ['resourceCateGuid', 'resourceCateCode']
        },

        {
          type: 4,
          label: '乡镇',
          itemKey: 'enterpriseName', // 关联cache
          resKey: 'name',
          url: 'capitalUser/showEnterprise',
          placeholder: '请选择',
          value: '',
          opintion: [],
          showLabel: 'name',
          bindKey: ['enterpriseGuid', 'enterpriseCode'],
          bindKeyRes: ['enterpriseGuid', 'enterpriseCode'],
          requestData: { // 单独设置请求参数
            userId: localStorage.getItem('xcUserId'),
            requestKey: 'enterprise' // 标识是乡镇（自用）
          }
        },

        {
          type: 4,
          label: '指标类型',
          itemKey: 'budgetcategoryName', // 关联cache
          resKey: 'budgetCategoryName',
          url: 'jc/getBudgetCategory',
          placeholder: '请选择',
          value: '',
          opintion: [],
          key: 'budgetCategoryCode',
          showLabel: 'budgetCategoryName',
          showValue: 'budgetCategoryCode',
          requestKey: 'budgetcategoryCode',
          bindKey: ['budgetcategoryGuid', 'budgetcategoryName'],
          bindKeyRes: ['budgetCategoryGuid', 'budgetCategoryName']
        },

        {
          type: 3,
          value: '',
          key: 'fileNo',
          label: '文号',
          placeholder: '请输入'
        },

        {
          type: 3,
          value: '',
          key: 'originalFileNo',
          label: '原文号',
          placeholder: '请输入'
        },

        {
          type: 3,
          value: '',
          key: 'money',
          label: '金额',
          placeholder: '请输入',
          inputType: 'number'
        },

        {
          type: 3,
          value: '',
          key: 'remark',
          label: '备注',
          placeholder: '请输入',
          inputType: 'textarea'
        },

        {
          type: 1,
          value: '',
          key: 'accountDate',
          label: '入账日期',
          placeholder: '请选择',
          inputType: 'date',
          valueFormatter: 'yyyy-MM-dd'
        },

        {
          type: 7,
          value: '',
          key: 'fileList',
          label: '附件'
        }
      ]

    };
  },
  computed: {
    isEditDialogShow() {
      return this.connectStore.value.isEditDialogShow;
    }
  },

  watch: {
    'connectStore.value.isEditDialogShow': {
      handler: function(v) {
        if (v) {
          this.cacheItem = _.cloneDeep(this.connectStore.value.rowNow);
          this.initData(this.cacheItem);
        }
      }
    }
  },
  mounted() {
    this.chooseYear = localStorage.getItem('chooseYear');
  },
  methods: {
    handleSelect(v, row) {
      row.programCode = v.programCode;
    },
    // 项目名称输入
    querySearchAsync(query, cb, row) {
      row.programCode = '';
      if (query) {
        getCommonDataSource({
          programName: query
        }, 'budget/in/getProgramList').then(res => {
          if (res.success) {
            res.data.forEach(item => {
              item.value = item.programName;
            });
            this.programOption = res.data;
            cb(res.data);
          } else {
            cb([]);
            this.programOption = [];
          }
        });
      } else {
        this.programOption = [];
        cb([]);
      }
    },

    inputCompleteBlur(programName, row) {
      if (programName) {
        getCommonDataSource({ programName }, 'budget/in/getProgram').then(res => {
          if (res.success) {
            row.programCode = res.data.programCode;
          }
        });
      }
    },
    changeSelectTreeData({ item, data }) {
      this.changeCacheItem(data, item.bindKey, item.bindKeyRes);
    },

    getSelectFouce(item) {
      if (!item.opintion.length) {
        this.selectOpintionRequest(item.url, item).then(list => {
          list.forEach((item1, index) => {
            this.$set(item.opintion, index, item1);
          });
        });
      }
    },

    selectOpintionRequest(url, { requestData: params }) {
      const requestData = {
        year: this.chooseYear,
        enterGuid: JSON.parse(localStorage.getItem('enterprise_jc'))[0].ENTERPRISE_GUID,
        userId: localStorage.getItem('xcUserId')
      };
      return getCommonDataSource(params || requestData, url).then(res => {
        if (res.success) {
          // 单独对乡镇数据进行过滤 （目前就乡镇特殊处理）
          if (params) {
            if (params.requestKey === 'enterprise') {
              res.data = res.data.filter(item => item.isCheck === 1);
              res.data.forEach(item => {
                item.enterpriseCode = item.label.split(' ')[0];
              });
            }
          }
          return Promise.resolve(res.data);
        }
      });
    },

    selectChange(value, item) {
      const selItem = item.opintion.find(item1 => {
        return item1[item.resKey] === value;
      });
      this.changeCacheItem(selItem, item.bindKey, item.bindKeyRes, item);
    },

    changeCacheItem(selItem, bindKey, bindKeyRes, config) {
      bindKey.forEach((key, index) => {
        this.cacheItem[key] = selItem[bindKeyRes[index]];
      });

      this.otherConfig(config, this.cacheItem, selItem);
    },

    // 是否还有其他操作
    otherConfig(config, row, selNow) {
      const { requestData } = config;
      // 下拉选择乡镇  联动归口
      if (requestData && requestData.requestKey === 'enterprise') {
        this.selectOpintionRequest('capital/getDivisionByEnter', {
          requestData: {
            year: this.chooseYear,
            isbnCode: selNow.enterpriseCode
          }
        }).then(list => {
          if (Array.isArray(list) && list.length) {
            const bindKey = ['divisionGuid', 'divisionName'];
            const bindKeyRes = ['divisionGuid', 'divisionName'];
            this.rowBind(row, bindKey, bindKeyRes, list[0]);
          }
        });
      }
    },

    rowBind(row, bindKey, bindKeyRes, selNow) {
      bindKey.forEach((key, index) => {
        row[key] = selNow[bindKeyRes[index]];
      });
    },

    onFileView(file) {
      console.log(file);
    },

    onFileChange(file, fileList, item) {
      this.cacheItem[item.key] = fileList;
    },

    onFileRemove({ name }, fileList) {
      return this.$confirm('确认删除该文件？')
        .then(() => {
          const index = this.cacheItem.fileList.findIndex(file => file.name === name);
          this.cacheItem.fileList.splice(index, 1);
          this.$message.warning('提交修改后完成删除');
          return Promise.resolve(true);
        })
        .catch(() => {
          return Promise.reject(false);
        });
    },

    dialogClose() {
      this.connectStore.value.isEditDialogShow = false;
    },

    initData(item) {
      this.formColunms.forEach(col => {
        if (col.key in item) {
          if (col.type === 1) {
            item[col.key] = item[col.key] + '';
          }
        }

        if (col.type === 7) {
          let fileList = [];
          if (item.annex) {
            const fileNames = item.annex.split(',').reduce((prev, curr) => {
              prev.push({ name: curr });
              return prev;
            }, []);
            fileList = fileList.concat(fileNames);
          }
          item.fileList = fileList;
        }
      });
    },

    // 验证提交
    submitReg(data) {
      let flag = true;
      const notNull = {
        year: {
          label: '年份'
        },
        enterpriseName: {
          label: '乡镇'
        },
        divisionName: {
          label: '归口'
        },
        programName: {
          label: '项目名称'
        },
        resourceName: {
          label: '资金来源'
        },
        budgetcategoryName: {
          label: '指标类型'
        },
        money: {
          label: '金额'
        },
        fileNo: {
          label: '文号'
        },
        postFileDate: {
          label: '发文日期'
        },
        accountDate: {
          label: '入账日期'
        }
      };
      const notNullArr = Object.keys(notNull);
      const dataKeyArr = Object.keys(data);
      for (let index = 0; index < dataKeyArr.length; index++) {
        const key = dataKeyArr[index];
        const value = data[key];
        if (value === '' || value === null) {
          if (notNullArr.includes(key)) {
            this.$message.warning(`${notNull[key].label} 不能为空`);
            flag = false;
            break;
          }
        }
        if (key === 'fileList') {
          for (let j = 0; j < value.length; j++) {
            const fileCurr = value[j];
            if (!flag) {
              break;
            }
            for (let k = j + 1; k < value.length; k++) {
              const fileNext = value[k];
              if (fileNext.name === fileCurr.name) {
                flag = false;
                this.$message.warning('不能上传相同文件: ' + fileNext.name);
                break;
              }
            }
          }
        }
      }
      return flag;
    },

    submit() {
      const { cacheItem } = this;
      if (!this.submitReg(cacheItem)) {
        return;
      }
      this.cacheItem.parent = null;
      this.cacheItem.annex = this.cacheItem.fileList.reduce((prev, curr, index) => {
        prev += curr.name;
        if (index !== this.cacheItem.fileList.length - 1) {
          prev += ',';
        }
        return prev;
      }, '');

      // todo 多文件上传相关参数
      const guid = [];
      const newUploadFiles = cacheItem.fileList.filter(file => file.raw);
      guid.length = newUploadFiles.length;
      guid.fill(this.connectStore.value.fileUpGuidAddition + cacheItem.guid);
      const files = newUploadFiles.map(file => file.raw);
      const upfileRequest = new FormData();
      for (let i = 0; i < files.length; i++) {
        upfileRequest.append('files', files[i]);
      }
      upfileRequest.append('guid', guid.join(','));
      this.submitLoading = true;
      editBudget(this.cacheItem).then(res => {
        if (res.success) {
          this.$message.success(res.message);
          uploadMulti(upfileRequest).then(res => {
            this.submitLoading = false;
            if (res.success) {
              this.$message.success(res.message);
              setTimeout(() => {
                this.$emit('editRowInfo', {
                  row: this.connectStore.value.rowNow,
                  edit: cacheItem
                });
                this.dialogClose();
              }, 500);
            }
          });
          this.$emit('editRowInfo', {
            row: this.connectStore.value.rowNow,
            edit: cacheItem
          });
          this.dialogClose();
        } else {
          this.submitLoading = false;
          this.$message.warning(res.message);
        }
      });
    }

  }
};
</script>

<style lang="scss" scoped>
.edit-title {
  display: flex;
  align-items: flex-end;
  > label {
    margin-right: 10px;
  }
  > div {
    font-size: 12px;
    color: rgba(0,0,0,0.45);
  }
}

.dialog-container {
  min-height: 500px;
  .edit-detailCode {
    font-size: 12px;
    color: rgba(0,0,0,0.45);
  }
  .edit-form {
    display: flex;
    justify-content: center;
  }
}

/deep/ .el-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #eaeefb;
  }

  .el-dialog__footer {
    padding: 10px 24px;
    border-top: 1px solid #eaeefb;
  }
}
</style>
